package com.lightningtrade.service.impl;

import com.lightningtrade.domain.SysOrder;
import com.lightningtrade.domain.SysProduct;
import com.lightningtrade.domain.SysUser;
import com.lightningtrade.mapper.SysOrderMapper;
import com.lightningtrade.mapper.SysProductMapper;
import com.lightningtrade.mapper.SysUserMapper;
import com.lightningtrade.service.SysOrderService;
import com.lightningtrade.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class SysOrderServiceImpl implements SysOrderService {

    @Autowired
    private SysOrderMapper orderMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysProductMapper sysProductMapper;

    @Transactional
    @Override
    public AjaxResult createOrder(SysOrder order) { // 商品下单逻辑

        // 1. 验证商品信息
        SysProduct sysProduct = sysProductMapper.selectProductById(order.getProductId());
        if (sysProduct == null) {
            return AjaxResult.error("商品信息不存在，创建订单失败！");
        }

        // 检查商品是否有效（可以根据实际情况，比如是否下架）
        if (sysProduct.getStatus() != 1) { // 假设 1 为有效商品状态
            return AjaxResult.error("商品不可用，创建订单失败！");
        }

        // 2. 验证用户信息
        SysUser user = userMapper.getUserByUid(order.getUid().toString());
        if (user == null) {
            return AjaxResult.error("用户信息不存在，创建订单失败！");
        }

        // 检查用户账户是否有效（可以根据实际情况，比如是否禁用）
        if (user.getStatus() != 0) { // 假设 0 为有效用户状态
            return AjaxResult.error("用户不可用，创建订单失败！");
        }

        // 3. 扣减库存
        int stockResult = orderMapper.decreaseStock(order.getProductId(), order.getProductQuantity());
        if (stockResult <= 0) {
            return AjaxResult.error("库存不足，创建订单失败！");
        }

        // 4. 插入订单
        int orderResult = orderMapper.createOrder(order);
        if (orderResult > 0) {
            order = orderMapper.selectOrderById(order.getId());
            return AjaxResult.success("订单创建成功", order);
        } else {
            // 如果订单创建失败，恢复库存
            orderMapper.restOreStock(order.getProductId(), order.getProductQuantity());
            return AjaxResult.error("订单创建失败");
        }
    }


    @Override
    public AjaxResult getOrderById(Long id) {
        SysOrder order = orderMapper.selectOrderById(id);
        if (order != null) {
            return AjaxResult.success("查询成功", order);
        } else {
            return AjaxResult.error("订单不存在");
        }
    }

    @Transactional// 事务注解
    @Override
    public AjaxResult cancelOrder(Long id) {
        // 查询订单
        SysOrder order = orderMapper.selectOrderById(id);
        if (order == null || order.getCancelStatus() == 1 || order.getCompleteStatus() == 1 || order.getPaymentStatus() == 0) {
            return AjaxResult.error("订单不存在或无法取消");
        }

        // 恢复库存和金额
        orderMapper.restOreStock(order.getProductId(), order.getProductQuantity());
        orderMapper.restOreUserBalance(order.getUid(), order.getTotalPrice());

        // 更新订单状态
        order.setCancelStatus(1);
        order.setCompleteStatus(1); // 标记为已完成
        int result = orderMapper.updateOrder(order);

        return result > 0 ? AjaxResult.success("订单取消成功") : AjaxResult.error("订单取消失败");
    }

    @Transactional
    @Override
    public AjaxResult payOrder(Long id) {
        // 1. 查询订单信息
        SysOrder order = orderMapper.selectOrderById(id);
        if (order == null) {
            return AjaxResult.error("订单不存在");
        }
        if (order.getPaymentStatus() == 1 || order.getCancelStatus() == 1) {
            return AjaxResult.error("订单已支付或已取消");
        }

        // 2. 查询用户信息
        SysUser user = userMapper.getUserByUid(order.getUid().toString());
        if (user == null) {
            return AjaxResult.error("用户不存在");
        }

        // 3. 判断用户余额是否足够
        if (user.getAccount().compareTo(order.getTotalPrice()) < 0) {
            return AjaxResult.error("余额不足，无法支付");
        }

        // 4. 扣减用户余额
        user.setAccount (user.getAccount() - order.getTotalPrice()); // 扣减余额
        int userUpdateResult = userMapper.updateUser(user); // 更新用户余额

        if (userUpdateResult <= 0) {
            return AjaxResult.error("扣减余额失败");
        }

        // 5. 更新订单支付状态
        order.setPaymentStatus(1); // 订单支付状态设为已支付
        int result = orderMapper.updateOrder(order); // 更新订单

        if (result > 0) {
            // 支付成功
            return AjaxResult.success("支付成功");
        } else {
            // 支付失败
            return AjaxResult.error("支付失败");
        }
    }

}
